# coding: utf-8

"""
    @Author :   zsj
    @File   :   main.py
    @Time   :   2024-08-06
"""

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from contextlib import asynccontextmanager
import uvicorn
from config import SETTINGS
from src.router.routers import routers
from src.core.session import SQLConSqlite
from src.common.exception import http_error_handler, http_422_error_handler, unicorn_exception_handler, UnicornException
from fastapi.middleware.cors import CORSMiddleware

ml_models = {}


# 异步内容管理，初始化数据库
@asynccontextmanager
async def lifespan(app: FastAPI):
    ml_models['init_db'] = SQLConSqlite().create_db_and_tables()
    yield
    ml_models.clear()

app = FastAPI(
    title=SETTINGS.PRO_TITLE,
    summary=SETTINGS.PRO_SUMMARY,
    description=SETTINGS.PRO_DESC,
    debug=SETTINGS.APP_DEBUG,
    version=SETTINGS.PRO_VERSION,
    # openapi_url=SETTINGS.PRO_OPENAPI_URL,
    lifespan=lifespan
)

# app.add_exception_handler(HTTPException, http_error_handler)
# app.add_exception_handler(RequestValidationError, http_422_error_handler)
# app.add_exception_handler(UnicornException, unicorn_exception_handler)

# 跨域资源请求中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=SETTINGS.CORS_ORIGINS,
    allow_credentials=SETTINGS.CORS_ALLOW_CREDENTIALS,
    allow_methods=SETTINGS.CORS_ALLOW_METHODS,
    allow_headers=SETTINGS.CORS_ALLOW_HEADERS,
)

# 载入路由
app.include_router(routers)


def run():
    uvicorn.run(app='main:app', host=SETTINGS.SERVER_HOST, port=SETTINGS.SERVER_PORT, reload=SETTINGS.SERVER_RELOAD)


if __name__ == '__main__':
    run()
